import { defineStore } from 'pinia'
import { ref } from 'vue'
import { menuStore } from '@/stores/menu.ts'
import { setItem, getItem, removeItem } from '@/utils/storage/index.ts'
import router from '@/router/index.ts'
import { tagViewStore } from '@/stores/tagViewStore.ts'
import { intersection } from 'lodash'

export const userStore = defineStore('user', () => {

  const token = ref(getItem('token'))
  const refreshToken = ref(getItem('refreshToken'))
  const userInfo = ref({} as any)
  // 权限
  const perms = ref([] as any)

  const setToken = (newToken: string) => {
    setItem('token', newToken)
    token.value = newToken
  }

  const setRefreshToken = (newRefreshToken: string) => {
    setItem('refreshToken', newRefreshToken)
    refreshToken.value = newRefreshToken
  }

  // todo zpd for real this data need fetch from backend
  const getUserInfo = () => {
    const menu = menuStore()
    userInfo.value = {
      id: '1',
      name: 'admin',
    }
    menu.initMenu()
    perms.value = [
      'myAdd',
      'myEdit',
      'myDelete',
      'myDetail',
      'myApply',
      'mySubmit'
    ]
  }

  const logout = () => {
    const tagView = tagViewStore()
    removeItem('token')
    removeItem('refreshToken')
    userInfo.value = {}
    perms.value = []
    token.value = ''
    refreshToken.value = ''
    tagView.resetTagView()
  }

  const login = (data) => {
    const menu = menuStore()
    console.log(data)
    setToken('token123123123')
    setRefreshToken('refreshToken123123123')
    getUserInfo()
    router.push(menu.dynamicRoute[0].path)
  }

  const hasPerms = (name: string | Array<string> | undefined) => {
    if (typeof name === 'string') {
      return perms.value.includes(name)
    } else if (Array.isArray(name)) {
      return intersection(name, perms.value).length !== 0
    }
    return true
  }

  return { token, refreshToken, userInfo, perms, setToken, setRefreshToken, getUserInfo, logout, login, hasPerms }
})
